/**
 * Created by root on 2017-08-10. router-即信一览
 */
import React, { Component, PropTypes } from 'react';
import { Utility, GxIcon, GxSearchBar, TaskList, Refresh, ApiInfo } from 'components';
import { connect } from 'react-redux';
import * as CommonActions from 'redux/modules/reduxCommon';

@connect(
  state => ({
    Title: state.Common.Title,                                          // 标题
    UrlParams: state.Common.UrlParams,                                  // URL参数
    TaskListInfo: state.Common.TaskListInfo                             // 活动列表
  }),
  { ...CommonActions })

export default class GmessageView extends Component {
  static propTypes = {
    Title: PropTypes.string,                                            // 标题
    UrlParams: PropTypes.object,                                        // url 参数
    TaskListInfo: PropTypes.object,                                     // 活动列表
    onApiGet: PropTypes.func,                                           // Get请求
    onClearContent: PropTypes.func,                                     // clear content
  };

  constructor(props) {
    super(props);
    this.state = {
      RefreshComplete: true,
      NextDataComplete: true,
      __Index: 0,
      IsNoteData: false,                                                 // 判断有无数据
      TaskLists: [],                                                     // 处理之后的任务列表
    };
  }
  componentWillMount() {
    // this.__TaskListData();
    // setTimeout(() => {
    //   this.__InitData();
    // }, 0);
    const { onClearContent } = this.props;
    onClearContent('TaskAssignCondition');
  }

  componentDidMount() {
    this.state.IsMount = true;
    this.__InitData({}, true);
  }

  componentWillUnmount() {
    delete this.state.IsMount;
    const { onClearContent } = this.props;
    onClearContent('TaskAssignCondition');
  }

  /**
   * 初始化页面数据
   * @returns 
   * @memberof GmessageView
   */
  __InitData(condition, isNextData) {
    const { onApiGet, TaskListInfo } = this.props;
    if (!Utility.isFunction(onApiGet)) {
      return;
    }
    const __params = Object.assign({}, Utility.$getInitPageTurning(), condition || {});
    const __self = this;
    const __ApiList = [];
    const { List } = TaskListInfo || {};
    if (document.body.scrollTop === 0 || !Utility.isArray(List) || !!isNextData) {
      __ApiList.push(onApiGet('TaskListInfo', ApiInfo.Task.TaskLists, { params: __params }));
    }
    if (!isNextData) {
      Utility.$loadingHide();
    } else {
      Utility.$loading();
    }
    Promise.all(__ApiList).then(() => {
      __self.__TaskListData();
      __self.__JudgeIsExistData();
      __self.state.RefreshComplete = true;
      __self.state.NextDataComplete = true;
      __self.__UpdateRender();
      Utility.$loadingHide();
    }).catch((ex) => {
      __self.__JudgeIsExistData();
      __self.state.RefreshComplete = true;
      __self.state.NextDataComplete = true;
      __self.__UpdateRender();
      Utility.$loadingHide();
      console.log(ex);
    });
  }

  /**
   * 判断有无数据列表
   * 
   * @returns 
   * @memberof GmessageView
   */
  __JudgeIsExistData() {
    const { TaskListInfo } = this.props;
    if (TaskListInfo) {
      if (Utility.isArray(TaskListInfo.List)) {
        return;
      }
    }

    this.state.IsNotData = true;
  }

  /**
   * 上拉加载
   * @memberof GmessageView
   */
  __HandlerNextData() {
    const { TaskListInfo } = this.props;
    const { Condition } = TaskListInfo;
    const { IsExistsNextData } = Condition;
    if (!IsExistsNextData) {
      return;
    }
    this.state.NextDataComplete = false;
    this.__InitData(Condition, true);
    this.__UpdateRender();
  }

  /**
   * 下拉刷新
   * @memberof GmessageView
   */
  __HandlerRefreshData() {
    const __params = Object.assign({}, Utility.$getInitPageTurning());
    this.state.RefreshComplete = false;
    this.__InitData(__params, false);
    this.__UpdateRender();
  }

  /**
   * 更新渲染
   */
  __UpdateRender() {
    if (!!this.state.IsMount) {
      this.setState({ __CurrentTempDate: new Date().getTime() });
    }
  }

  /**
   * 更新state
   * 
   * @param {any} type 
   * @memberof GmessageView
   */
  __UpdateState(type) {
    if (type) {
      this.state[type] = !this.state[type];
    }
    this.__UpdateRender();
  }

  /**
   * 页面跳转。
   * @param params
   * @private GmessageView
   */
  __HandlerGoToPage(url, params) {
    Utility.toPage(url, params);
  }

  /**
   * 搜索事件
   * 
   * @param {any} key 
   * @returns 
   * @memberof GmessageView
   */
  __HandlerSearch(key) {
    this.state.KeyWord = key;
    if (key === '') {
      this.__UpdateRender();
      return;
    }
    this.__UpdateRender();
    // __search.title = encodeURIComponent(this.state.KeyWord);
  }

  /**
   * 搜索取消
   * 
   * @memberof GmessageView
   */
  __Cancel() {
    console.log('取消');
    // Utility.$goBack();
  }

  /**
   * IsToPage 跳转到搜索页面
   * 
   * @memberof GmessageView
   */
  __HandlerClickTo(type) {
    const { UrlParams } = this.props;
    const { token } = UrlParams || {};
    let __token = '';
    if (token) {
      __token = token;
    }
    const { SearchPage } = Utility.constItem.UrlItem;
    if (SearchPage) {
      Utility.toPage(SearchPage, { type: type, token: __token });
    }
  }

  /**
   * 按照年月树状结构处理数据
   * 
   * @returns 每个月对应的数据集合 
   * @memberof TaskList
   */
  __TaskListData() {
    // const { TaskLists } = this.state;
    const { TaskListInfo } = this.props;
    const { List } = TaskListInfo || {};
    const TaskLists = List || [];
    if (!Utility.isArray(TaskLists)) {
      return;
    }
    const monthOfYear = ['12月', '11月', '10月', '09月', '08月', '07月', '06月', '05月', '04月', '03月', '02月', '01月'];
    const __formatMonth = 'yyyy年MM月';
    // const __formatDay = 'yyyy年MM月dd日';
    const resultMonth = [];
    let result = [];
    for (let i = 0; i < monthOfYear.length; i++) {
      result = [];
      const item = monthOfYear[i];
      for (let j = 0; j < TaskLists.length; j++) {
        const row = TaskLists[j];
        const __createTimeMonth = Utility.$convertToDateByTimestamp(row.createTime, __formatMonth) + '';
        const month = __createTimeMonth.slice(-3);
        if (item === month) {
          result.push(row);
        }
        // break;
      }
      if (result.length !== 0) {
        resultMonth.push(result);
      }
    }
    // console.log(resultMonth);
    if (!Utility.isArray(resultMonth)) {
      return;
    }
    this.setState({ TaskLists: resultMonth });
  }

  /**
   * 遍历月份对应的任务列表
   * 
   * @param {any} styles 
   * @returns 
   * @memberof GmessageView
   */
  __TaskListMapHtml(styles) {
    const { TaskLists } = this.state;
    if (!Utility.isArray(TaskLists)) {
      return null;
    }
    return TaskLists.map((list, index) => {
      const listOne = list[0] || [];
      const { createTime } = listOne || {};
      // console.log(createTime);
      return (
        <div className={styles.listItemCss} key={'list_item_' + index}>
          <TaskList TaskLists={list} createTime={createTime} />
        </div>
      );
    });
  }

  render() {
    const styles = require('./scss/GmessageView.scss');
    const { RefreshComplete, NextDataComplete } = this.state;

    return (
      <div className={styles.messageViewCss}>
        <div className={styles.searchContainer}>
          <div className={styles.screening} onClick={this.__HandlerClickTo.bind(this, 0)}>
            <div className={styles.screen}>筛选</div>
            <div>
              <GxIcon IconType="iconDown" />
            </div>
          </div>
          <div className={styles.search}>
            <GxSearchBar ref="searchBar" Title="搜索" IsToPage IsHideCancel onClick={this.__HandlerClickTo.bind(this, 1)} onSearch={this.__HandlerSearch.bind(this)} onCancel={this.__Cancel.bind(this)} />
          </div>
        </div>
        <Refresh Percentage={20} MarginBottom={20} RefreshComplete={RefreshComplete} NextDataComplete={NextDataComplete}
          onNextData={this.__HandlerNextData.bind(this)}
          onRefresh={this.__HandlerRefreshData.bind(this)}>
          <div className={styles.container}>
            {this.__TaskListMapHtml(styles)}
          </div>
        </Refresh>
      </div>
    );
  }
}

